// pages/supermarket-details/details.js
import {
  ajax,
  src,
  util
} from "../../utils/util.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {

    juanshow: false,

    clickcat: false,
    showsxselect: false,
    shopID: "",
    ID:"",
    details:'',
    IsCollection:'',
    carall:"",
    quedingcanclick:true,
    canclick:true,

    canadddandugoods:true,
    canminusdandugoods:true
  },


  addselfnum: function (e) {
    if (!this.data.canadddandugoods){
      console.log("donggan")
      return
    }
    this.setData({
      canadddandugoods:false
    })


    var index = 0;
    // if (this.data.nr.details[index].selfnum==0){

    // }else{

    // }
    var ProNums = this.data.details[index].ProNums + 1
    console.log(ProNums)
    var str = "details[" + index + "].ProNums"
    this.setData({
      [str]: ProNums
    })
    this.clickadd(index)
  },


  minusselfnum: function (e) {
    if (!this.data.canminusdandugoods) {
      console.log("donggan")
      return
    }
    this.setData({
      canminusdandugoods: false
    })



    var index = 0;
    if (this.data.details[index].ProNums == 0) {
      return
    } else {
      var ProNums = this.data.details[index].ProNums - 1
      console.log(ProNums)
      var str = "details[" + index + "].ProNums"
      this.setData({
        [str]: ProNums
      })
    }
    this.updatacarnum1(index, 2)
  },
  // NR
  updatacarnum1: function (index, VType) {
    ajax('/api/ShopCart/UpdateNums?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      ShopID: this.data.ID,

      SKUID: 0,
      ProuductPublishID: this.data.details[index].ID,
      OrderNumber: VType == 1 ? this.data.details[index].ProNums : this.data.details[index].ProNums,
      ID: this.data.details[index].CartID,
      VType: VType
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "post",
      }, res => {
        console.log(res)

        if (res.Message == "库存不足") {
          this.getdetails()
          wx.showToast({
            title: res.Message,
            icon: 'none',
            duration: 1000
          })
        } else if (res.Message == "上传失败") {
          
          this.getdetails()

          wx.showToast({
            title: res.Message,
            icon: 'none',
            duration: 1000
          })
        } else if (res.Message == "上传成功!") {
          this.getcart()
          this.getdetails()
        }


      })
  },

  clickcatfun: function () {
    this.setData({
      clickcat: !this.data.clickcat
    })

    if (this.data.clickcat == true) {
      this.getcart()
    }
  },


  // 领劵框显示
  lingjuankuang: function (e) {
    this.setData({
      juanshow: true
    })
    var ptid = e.currentTarget.dataset.ptid;
    this.setData({
      id: ptid
    })
    console.log(112)
    // console.log(ptid,'ptid')
    this.getjuan();

  },


  hiddenkuang: function () {
    this.setData({
      juanshow: false
    })
  },
  getjuan: function () {
    ajax('/api/CouponCollection/Get?requestContent=' + JSON.stringify({
      Vtype: 3,
      ActivityIDStr: this.data.details[0].ID,
      PageIndex: 0,
      ProvinceName: wx.getStorageSync('address_component').province,
      CityName: wx.getStorageSync('address_component').city,
      DistrictName: wx.getStorageSync('address_component').district,
      Title: "",
      token: wx.getStorageSync('Access_token')
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        // console.log(res)
        if (res.Models!=null){
          var coupon = []
          for (var x in res.Models) {
            if (res.Models[x].CouponType != 2) {
              coupon.push(res.Models[x])
            }
          }
          this.setData({
            coupon: coupon
          })
        }

        for (var a in this.data.coupon) {
          this.setData({
            beginnyr: this.data.coupon[a].Bdate.slice(0, 10),
            endnyr: this.data.coupon[a].Edate.slice(0, 10)
          })
        }
      })
  },
  //分享领取
  lijifenxiang: function (e) {
    var UserCouponID = e.currentTarget.dataset.id

    ajax('/api/UploadReceiveCouponPrimary/UploadAdd?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      UserCouponID: UserCouponID,
      ProvinceName: wx.getStorageSync('address_component').province,
      CityName: wx.getStorageSync('address_component').city,
      DistrictName: wx.getStorageSync('address_component').district,

    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "post",
      }, res => {
        console.log(res)
        if (res.Message == "上传成功!") {
          var id = UserCouponID;

          var rid = res.Status

          console.log(rid)
          wx.navigateTo({
            url: '/pages/unpacking-securities/securities?id=' + id + '&rid=' + rid,
          })
        }
      })


  },
  // 立即领取
  lingjuan: function (e) {
    let id = e.currentTarget.dataset.id
    // console.log(id,'id')
    ajax('/api/UploadReceiveCouponPrimaryNew/UploadAdd?requestContent=' + JSON.stringify({
      token: wx.getStorageSync("Access_token"),
      ProvinceName: wx.getStorageSync('address_component').province,
      CityName: wx.getStorageSync('address_component').city,
      DistrictName: wx.getStorageSync('address_component').district,
      UserCouponID: id
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "post",
      }, res => {
        console.log(res, 'res')
        wx.showToast({
          title: '成功',
          icon: 'success',
          duration: 2000
        })
        this.getjuan()
      })
  },

  getcart: function () {
    ajax('/api/ShopCart/GetShopCart?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      ShopID: this.data.shopID,
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        // console.log(res)

        this.setData({
          carlist: res.Models
        })
        //检测是否为全选
        for (var x in this.data.carlist) {
          if (this.data.carlist[x].IsChecked == false) {
            this.setData({
              selectall: false
            })
            break
          }
          this.setData({
            selectall: true
          })
        }
        this.jisuanallmoney()
      })
  },

  selectall: function (index = 1) {
    // console.log(index)
    this.quanxuan(!this.data.selectall)
    this.setData({
      selectall: !this.data.selectall
    })
  },

  clearcart() {
    ajax('/api/ShopCart/DelCart?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      ShopID: this.data.shopID,
      Type: 1,
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "post",
      }, res => {
        console.log(res)
        this.getcart()
        this.getdetails()
      })
  },


  jisuanallmoney: function () {
    var allmoney = 0
    var yixuan = 0
    var carall = 0
    for (var x in this.data.carlist) {
      if (this.data.carlist[x].IsChecked) {
        var danpinjia = (this.data.carlist[x].IMoney*100) * this.data.carlist[x].OrderNumber
        
        console.log(danpinjia)

        allmoney = allmoney*100+ danpinjia
        // console.log(allmoney)
        allmoney = allmoney/100

        yixuan += this.data.carlist[x].OrderNumber
      }
      carall += this.data.carlist[x].OrderNumber
    }
    console.log(allmoney)
    this.setData({
      allmoney: allmoney.toFixed(2),
      yixuan: yixuan,
      carall: carall
    })
  },


  // #########################################################
  // CARLIST
  updatacarnum: function (index, VType) {
    ajax('/api/ShopCart/UpdateNums?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      ShopID: this.data.ID,

      SKUID: this.data.carlist[index].SKUID,
      ProuductPublishID: this.data.carlist[index].ProuductPublishID,
      OrderNumber: VType == 1 ? this.data.carlist[index].OrderNumber + 1 : this.data.carlist[index].OrderNumber - 1,
      ID: this.data.carlist[index].ID,
      VType: VType
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "post",
      }, res => {
        console.log(res)
        if (res.Message == "库存不足") {
          wx.showToast({
            title: res.Message,
            icon: 'none',
            duration: 1000
          })
        }
        this.getcart()
        this.getdetails()
      })
  },

  //car add
  caradd: function (e) {
    var index = e.currentTarget.dataset.index
    this.updatacarnum(index, 1)
  },
  carminus: function (e) {
    var index = e.currentTarget.dataset.index
    this.updatacarnum(index, 2)
  },
// ###########################

  //收藏
  shoucang:function(e){
    console.log(e.currentTarget.dataset)
    var idx = e.currentTarget.dataset.pgid;
    console.log(idx,123)
    if (this.data.IsCollection == 0) {
        ajax('/api/CollecIns/Insert?requestContent=' + JSON.stringify({
          token: wx.getStorageSync("Access_token"),
          PGID: idx,
          VType: 5
        }), {
            header: {
              'Accept': 'application/x-www-form-urlencoded', // 默认值
            },
            method: "post",
          }, res => {
            this.getdetails()
          })
      } else {
        ajax('/api/CollecDel/Del?requestContent=' + JSON.stringify({
          token: wx.getStorageSync("Access_token"),
          PGID: idx,
          VType: 4
        }), {
            header: {
              'Accept': 'application/x-www-form-urlencoded', // 默认值
            },
            method: "post",
          }, res => {
            console.log(res, 'res')
            this.getdetails()
          })
      }

  },
  // 联系商家
  lianxishangjia:function(e){
    var phone = e.currentTarget.dataset.phone
    wx.makePhoneCall({
      phoneNumber: phone 
    })
  },
  //获取商品详情
  getdetails:function(){
    ajax('/api/ShopProduct/GetShopProductDetail?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      ShopID: this.data.shopID,
      ProuductPublishID: this.data.ID,
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "get",
      }, res => {
        // console.log(res)
        this.setData({ details: res.Models })


        this.setData({
          canadddandugoods: true,
          canminusdandugoods: true
        })
        for (var a in this.data.details) {
          console.log(this.data.details[a].IsCollection,1111)
          this.setData({
            IsCollection: this.data.details[a].IsCollection
          })
          // console.log(this.data.shopdetails[a].PT_CGTZ.length)
        }
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */

  showsxselect: function () {
    var showsxselect=this.data.showsxselect
    this.setData({
      showsxselect: !showsxselect
    })
    if (this.data.showsxselect == true) {
      this.setData({
        quedingcanclick: true
      })
    }
  },

  copyobj: function (a) {
    var c = {};
    c = JSON.parse(JSON.stringify(a));
    return c;
  },

  // 添加购物车
  clickadd: function () {
    var info = this.data.details[0]
    console.log(info.IsSku)

    // console.log("11111111111")
    //有属性
    if (info.IsSku>0) {
      if (info.SkuName.length == 2) {
        // 有附加属性选择
        var obj = {}
        obj.stylelength = 2
        
        var SkuName = info.SkuName
        var SKUImgList = info.SKUImgList
        var canuselist = []
        for (var x in SKUImgList) {
          canuselist.push(SKUImgList[x].ANVS)
        }
        // obj.push(SkuName[0].AVName)
        for (var x in SkuName) {
          if (x == 0) {
            obj.yiji = SkuName[x].AVName
            obj.yijiANName = SkuName[x].ANName
            obj.selfnum = 1
          } else if (x == 1) {
            for (var y in obj.yiji) {
              var newlist = this.copyobj(SkuName[x].AVName)
              for (var m in newlist) {
                newlist[m].zi = obj.yiji[y].AVID + '_' + newlist[m].AVID
                // console.log(newlist[m].zi)
                if (canuselist.indexOf(newlist[m].zi) != -1) {
                  newlist[m].canuse = true
                  newlist[m].other = SKUImgList[canuselist.indexOf(newlist[m].zi)]
                  newlist[m].isselect = false
                } else {
                  newlist[m].canuse = false
                  newlist[m].isselect = false
                }
              }
              obj.yiji[y].xiaji = newlist
              obj.yiji[y].xiajiname = SkuName[x].ANName
              obj.yiji[y].isselect = false
            }
          }
          obj.yiji[0].isselect = true
          for (var x in obj.yiji[0].xiaji) {
            if (obj.yiji[0].xiaji[x].canuse) {
              obj.yiji[0].xiaji[x].isselect = true

              obj.morenselect = obj.yiji[0].xiaji[x].other
              break
            }
          }
        }
        console.log(canuselist)
        console.log(obj)
        this.setData({
          obj: obj
        })
      } else if (info.SkuName.length == 1) {
        var obj = {}
        obj.stylelength = 1
        obj.selfnum = 1
       
        var SkuName = info.SkuName
        var SKUImgList = info.SKUImgList
        var canuselist = []
        for (var x in SKUImgList) {
          canuselist.push(SKUImgList[x].ANVS)
        }
        console.log(canuselist)
        for (var x in SkuName) {
          var newlist = this.copyobj(SkuName[x].AVName)
          for (var y in newlist) {
            newlist[y].zi = newlist[y].AVID + "_" + "0"
            if (canuselist.indexOf(newlist[y].zi) != -1) {
              newlist[y].canuse = true
            } else {
              newlist[y].canuse = false
            }
            newlist[y].isselect = false
            newlist[y].other = SKUImgList[canuselist.indexOf(newlist[y].zi)]
          }
          for (var y in newlist) {
            if (newlist[y].canuse == true) {
              newlist[y].isselect = true

              obj.morenselect = newlist[y].other
              break
            }
          }

          // obj.yiji[0].isselect = true
          obj.yijiANName = SkuName[x].ANName
          obj.yiji = newlist

        }

        console.log(canuselist)
        console.log(obj)

        this.setData({
          obj: obj
        })

      }
      this.showsxselect()
    } else {
      // 无附加属性 

      this.addcart("",1)
    }

  },

 
  addcart: function ( SKUID = "", OrderNumber = 1) {
    var info = this.data.details[0]
    if (SKUID == "") {
      console.log("yopushuxi")
      ajax('/api/ShopCart/AddCart?requestContent=' + JSON.stringify({
        token: wx.getStorageSync('Access_token'),
        ShopID: this.data.shopID,
        ProuductPublishID: info.ID,
        ProductID: info.ProductID,
        OrderNumber: OrderNumber,
        IMoney: info.PrevsufferingPrice,
        OriPrice: info.OriPrice,
      }), {
          header: {
            'Accept': 'application/x-www-form-urlencoded', // 默认值
          },
          method: "post",
        }, res => {

          // 1：成功 0：失败 2：商品无货，请选择其他商品 / 商品已下架，请选择其他商品 3：该商户已停用

          if (res.Status==1){
            this.getdetails()
            this.getcart()
          } else if (res.Status==0){
            this.setData({
              quedingcanclick: true
            })
            wx.showToast({
              title: "添加失败",
              icon: 'none',
              duration: 2000
            })
            this.getdetails()
           
          } else if (res.Status == 2) {
            this.setData({
              quedingcanclick: true
            })
            wx.showToast({
              title: "库存不足",
              icon: 'none',
              duration: 2000
            })
            this.getdetails()
            
          }

          console.log(res)
          
          // this.showsxselect()
        })
    } else {

      console.log("wushuxi")
      ajax('/api/ShopCart/AddCart?requestContent=' + JSON.stringify({
        token: wx.getStorageSync('Access_token'),

        ShopID: this.data.shopID,

        ProuductPublishID: info.ID,
        ProductID: info.ProductID,
        SKUID: SKUID,
        OrderNumber: OrderNumber,
        IMoney: this.data.obj.morenselect.PrevsufferingPrice,
        OriPrice: info.OriPrice,
      }), {
          header: {
            'Accept': 'application/x-www-form-urlencoded', // 默认值
          },
          method: "post",
        }, res => {
          console.log(res)
          console.log("1111111111111111")


          if (res.Status == 1) {
            // this.getcart()
            this.getdetails()
            this.getcart()
            this.showsxselect()

          } else if (res.Status == 0) {
            wx.showToast({
              title: "添加失败",
              icon: 'none',
              duration: 2000
            })
            this.getdetails()
            this.setData({
              quedingcanclick: true
            })

          } else if (res.Status == 2) {
            wx.showToast({
              title: "库存不足",
              icon: 'none',
              duration: 2000
            })
            this.getdetails()
            this.setData({
              quedingcanclick: true
            })
          }
        })


    }
  },


  selectyiji: function (e) {
    var index = e.currentTarget.dataset.index
    var str = "obj.yiji[" + index + "].isselect"
    for (var x in this.data.obj.yiji) {
      var str1 = "obj.yiji[" + x + "].isselect"
      this.setData({
        [str1]: false
      })
    }
    this.setData({
      [str]: true
    })


    for (var x in this.data.obj.yiji) {
      for (var y in this.data.obj.yiji[x].xiaji) {
        var str11 = "obj.yiji[" + x + "].xiaji[" + y + "].isselect"
        this.setData({
          [str11]: false
        })
      }
    }

    for (var x in this.data.obj.yiji) {
      if (this.data.obj.yiji[x].isselect) {
        for (var aa in this.data.obj.yiji[x].xiaji) {
          if (this.data.obj.yiji[x].xiaji[aa].canuse == true) {
            var str12 = "obj.yiji[" + x + "].xiaji[" + aa + "].isselect"
            this.setData({
              [str12]: true
            })
            var str111 = "obj.morenselect"
            this.setData({
              [str111]: this.data.obj.yiji[x].xiaji[aa].other
            })
            break
          }
        }
      }
    }


  },

  selectyiji1: function (e) {
    var index = e.currentTarget.dataset.index
    var str = "obj.yiji[" + index + "].isselect"
    for (var x in this.data.obj.yiji) {
      var str1 = "obj.yiji[" + x + "].isselect"
      this.setData({
        [str1]: false
      })
    }
    this.setData({
      [str]: true
    })

    for (var y in this.data.obj.yiji) {
      if (this.data.obj.yiji[y].isselect == true) {
        var str1111 = "obj.morenselect"
        this.setData({
          [str1111]: this.data.obj.yiji[y].other
        })
        return
      }
    }

  },

  selecterji: function (e) {
    var index = e.currentTarget.dataset.index

    console.log(index)
    for (var x in this.data.obj.yiji) {
      for (var y in this.data.obj.yiji[x].xiaji) {
        var str11 = "obj.yiji[" + x + "].xiaji[" + y + "].isselect"
        this.setData({
          [str11]: false
        })
      }
    }
    for (var x in this.data.obj.yiji) {
      if (this.data.obj.yiji[x].isselect) {
        var str12 = "obj.yiji[" + x + "].xiaji[" + index + "].isselect"
        this.setData({
          [str12]: true
        })
        var str111 = "obj.morenselect"
        this.setData({
          [str111]: this.data.obj.yiji[x].xiaji[index].other
        })
      }
    }
  },


  onLoad: function (options) {
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#000',
    });

    var shopID = options.shopID
    var ID = options.ID

    this.setData({
      shopID: shopID,
      ID: ID
    });

    this.getdetails()
    this.getcart()

  },



  quanxuan: function (status) {
    for (var x in this.data.carlist) {
      if (this.data.carlist[x].IsChecked != status) {
        ajax('/api/ShopCart/UpdateChecked?requestContent=' + JSON.stringify({
          token: wx.getStorageSync('Access_token'),
          IsChecked: status,
          CartIDStr: this.data.carlist[x].ID
        }), {
            header: {
              'Accept': 'application/x-www-form-urlencoded', // 默认值
            },
            method: "post",
          }, res => {
            console.log(res)
            this.getcart()
          })
      }
    }
  },

  //修改选中状态

  updatedichecked: function (index) {
    ajax('/api/ShopCart/UpdateChecked?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      IsChecked: !this.data.carlist[index].IsChecked,
      CartIDStr: this.data.carlist[index].ID
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "post",
      }, res => {
        console.log(res)
        this.getcart()
      })
  },



  clickdanxuan: function (e) {
    var index = e.currentTarget.dataset.index
    this.updatedichecked(index)
  },

  tojiesuan: function () {

    if (this.data.canclick == false) {
      return
    }
    this.setData({
      canclick: false
    })

    // var query":[{"DealerID":39,"Orders":[{"PGID":372,"SKUID":733,"OrderNumber":1}]}],"
    var query = []
    var CartIDStr = ""
    var CartIDStrlist = []

    var DealerID = this.data.shopID
    var objhu = {}
    var Orders = []
    objhu.DealerID = DealerID

    for (var x in this.data.carlist) {
      if (this.data.carlist[x].IsChecked) {
        var obj = {}
        obj.PGID = this.data.carlist[x].ProuductPublishID
        obj.SKUID = this.data.carlist[x].SKUID
        obj.OrderNumber = this.data.carlist[x].OrderNumber
        Orders.push(obj)
        CartIDStrlist.push(this.data.carlist[x].ID)
      }
    }
    objhu.Orders = Orders
    query.push(objhu)
    CartIDStr = CartIDStrlist.join(",")

    ajax('/api/ShopCart/UpdateState?requestContent=' + JSON.stringify({
      token: wx.getStorageSync('Access_token'),
      CartIDStr: CartIDStr,
      query: query
    }), {
        header: {
          'Accept': 'application/x-www-form-urlencoded', // 默认值
        },
        method: "post",
      }, res => {
        console.log(res)
        if (res.Message == "上传成功!") {
          wx.navigateTo({
            url: '/pages/sureorder/sureorder?CartIDStr=' + CartIDStr,
          })
        } else {
          this.setData({
            canclick:true
          })
          wx.showToast({
            title: res.Message,
            icon: 'none',
            duration: 2000
          })
        }
        // console.log("11111111111111111111111111111")

      })
  },

  addobjselfnum: function () {
    var str = "obj.selfnum"
    this.setData({
      [str]: this.data.obj.selfnum + 1
    })
  },

  minusobjselfnum: function () {
    if (this.data.obj.selfnum != 1) {
      var str = "obj.selfnum"
      this.setData({
        [str]: this.data.obj.selfnum - 1
      })
    } else {
      return
    }

  },

  addcartbefor: function () {
    if(!this.data.quedingcanclick){
      console.log("donggan")
      return
    }

    this.setData({
      quedingcanclick:false
    })

    if (this.data.obj.morenselect){
      this.addcart(this.data.obj.morenselect.SKUID, this.data.obj.selfnum)
    }else{
      this.addcart("", this.data.obj.selfnum)
    }
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getdetails()
    this.getcart()
    this.setData({
      canclick: true
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})